package com.getpebble.android.jskit.webapps;

import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.getpebble.android.R;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.jskit.bridge.JsAppContextBridge;
import com.getpebble.android.jskit.webapps.JsKit.WebviewClientPack;
import com.getpebble.android.jskit.webapps.PebbleWebappBaseActivity.WebappIntentTypeE;
import com.getpebble.android.jskit.webapps.builtins.BlankApp;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Timer;
import java.util.UUID;
import org.json.JSONObject;

public class PebbleWebUiWebappActivity extends PebbleWebappBaseActivity {
    boolean dbgBackPressed = false;
    long dbgBackPressedTime = 0;
    WebappScenePagerAdapter mWebappScenePager = null;

    protected enum DebugEscapesOriginE {
        __INVALID__,
        onPause,
        onStop,
        onDestroy
    }

    public static class WebappScenePagerAdapter {
        int currentFrag = -1;
        WeakReference<Activity> mActivityBackRef;
        FragmentManager mFragmentManager = null;
        int mHostViewId = -1;
        protected HashMap<Integer, WebappGenericBaseFragment> mWebappSceneMapByUniqueId = null;
        protected ArrayList<WebappGenericBaseFragment> mWebappSceneSequenceListAccelerator = null;

        public WebappScenePagerAdapter(Activity hostActivity, int hostViewId) {
            this.mHostViewId = hostViewId;
            this.mActivityBackRef = new WeakReference(hostActivity);
            createWebappScenes();
        }

        public synchronized void addFragment(WebappGenericBaseFragment g) {
            if (g == null) {
                Trace.debug("PebbleWebappBaseActivity", "addFragment: g is null");
            } else if (this.mWebappSceneMapByUniqueId.containsKey(Integer.valueOf(g.clientUuidAsInt()))) {
                Trace.debug("PebbleWebappBaseActivity", "addFragment: duplicate");
            } else {
                this.mWebappSceneMapByUniqueId.put(Integer.valueOf(g.clientUuidAsInt()), g);
                this.mWebappSceneSequenceListAccelerator.add(g);
                FragmentManager fm = getFragmentManagerTempRef();
                FragmentTransaction ft = fm.beginTransaction();
                ft.disallowAddToBackStack();
                ft.replace(this.mHostViewId, g);
                this.currentFrag = this.mWebappSceneSequenceListAccelerator.size() - 1;
                ft.setTransition(4099);
                ft.commit();
                fm.executePendingTransactions();
            }
        }

        public synchronized WebappGenericBaseFragment removeFragment(UUID clientUuid) {
            WebappGenericBaseFragment webappGenericBaseFragment;
            if (clientUuid == null) {
                Trace.debug("PebbleWebappBaseActivity", "WebappGenericBaseFragment: clientUuid is null");
                webappGenericBaseFragment = null;
            } else {
                webappGenericBaseFragment = (WebappGenericBaseFragment) this.mWebappSceneMapByUniqueId.remove(Integer.valueOf(WebappGenericBaseFragment.clientUuidAsInt(clientUuid)));
                if (webappGenericBaseFragment == null) {
                    Trace.debug("PebbleWebappBaseActivity", "WebappGenericBaseFragment: f is null");
                    webappGenericBaseFragment = null;
                } else {
                    int targetFragIndex = this.mWebappSceneSequenceListAccelerator.indexOf(webappGenericBaseFragment);
                    if (targetFragIndex >= 0) {
                        this.mWebappSceneSequenceListAccelerator.remove(targetFragIndex);
                        FragmentManager fm = getFragmentManagerTempRef();
                        if (fm == null) {
                            Trace.debug("PebbleWebappBaseActivity", "WebappGenericBaseFragment: fm is null");
                        } else {
                            FragmentTransaction ft = fm.beginTransaction();
                            ft.disallowAddToBackStack();
                            if (this.currentFrag < 0 || this.currentFrag >= getCount()) {
                                this.currentFrag = targetFragIndex;
                            }
                            int nextIndex;
                            if (this.currentFrag == targetFragIndex) {
                                nextIndex = nextFragmentIndex(this.currentFrag);
                                if (nextIndex <= 0 || nextIndex == this.currentFrag) {
                                    ft.remove(webappGenericBaseFragment);
                                    this.currentFrag = -1;
                                } else {
                                    ft.replace(this.mHostViewId, (Fragment) this.mWebappSceneSequenceListAccelerator.get(nextIndex));
                                    this.currentFrag = nextIndex;
                                }
                            } else {
                                nextIndex = nextFragmentIndex(this.currentFrag);
                                ft.replace(this.mHostViewId, (Fragment) this.mWebappSceneSequenceListAccelerator.get(nextIndex));
                                this.currentFrag = nextIndex;
                            }
                            webappGenericBaseFragment.flagForSubsequentTeardownOnDestroy();
                            if (this.currentFrag == -1) {
                                fm.popBackStack();
                                ft.setTransition(8194);
                            } else {
                                ft.setTransition(4099);
                            }
                            ft.commitAllowingStateLoss();
                            fm.executePendingTransactions();
                        }
                    }
                }
            }
            return webappGenericBaseFragment;
        }

        private synchronized int nextFragmentIndex(int fromIndex) {
            if (this.mWebappSceneSequenceListAccelerator.size() >= 1) {
                if (this.mWebappSceneSequenceListAccelerator.size() == 1) {
                    fromIndex = 0;
                } else {
                    fromIndex = (fromIndex + 1) % this.mWebappSceneSequenceListAccelerator.size();
                }
            }
            return fromIndex;
        }

        private synchronized int previousFragmentIndex(int fromIndex) {
            if (this.mWebappSceneSequenceListAccelerator.size() >= 1) {
                if (this.mWebappSceneSequenceListAccelerator.size() == 1) {
                    fromIndex = 0;
                } else {
                    fromIndex = fromIndex <= 0 ? this.mWebappSceneSequenceListAccelerator.size() - 1 : fromIndex - 1;
                }
            }
            return fromIndex;
        }

        public synchronized void nextValidFragmentWithManager() {
            FragmentManager fm = getFragmentManagerTempRef();
            if (this.mWebappSceneSequenceListAccelerator.size() >= 1 && fm != null) {
                if (this.currentFrag < 0 || this.currentFrag >= this.mWebappSceneSequenceListAccelerator.size()) {
                    this.currentFrag = nextFragmentIndex(this.currentFrag);
                    if (this.currentFrag >= 0) {
                        FragmentTransaction ft = fm.beginTransaction();
                        ft.disallowAddToBackStack();
                        ft.replace(this.mHostViewId, (Fragment) this.mWebappSceneSequenceListAccelerator.get(this.currentFrag));
                        ft.setTransition(4099);
                        ft.commit();
                    }
                    fm.executePendingTransactions();
                }
            }
        }

        public synchronized void nextFragmentWithManager() {
            FragmentManager fm = getFragmentManagerTempRef();
            if (this.mWebappSceneSequenceListAccelerator.size() >= 1 && fm != null) {
                this.currentFrag = nextFragmentIndex(this.currentFrag);
                if (this.currentFrag >= 0) {
                    FragmentTransaction ft = fm.beginTransaction();
                    ft.disallowAddToBackStack();
                    ft.replace(this.mHostViewId, (Fragment) this.mWebappSceneSequenceListAccelerator.get(this.currentFrag));
                    ft.setTransition(4099);
                    ft.commit();
                }
                fm.executePendingTransactions();
            }
        }

        public synchronized void previousFragmentWithManager() {
            FragmentManager fm = getFragmentManagerTempRef();
            if (this.mWebappSceneSequenceListAccelerator.size() >= 1 && fm != null) {
                this.currentFrag = previousFragmentIndex(this.currentFrag);
                if (this.currentFrag >= 0) {
                    FragmentTransaction ft = fm.beginTransaction();
                    ft.disallowAddToBackStack();
                    ft.replace(this.mHostViewId, (Fragment) this.mWebappSceneSequenceListAccelerator.get(this.currentFrag));
                    ft.setTransition(4099);
                    ft.commit();
                }
                fm.executePendingTransactions();
            }
        }

        private FragmentManager getFragmentManagerTempRef() {
            if (this.mFragmentManager != null) {
                return this.mFragmentManager;
            }
            if (this.mActivityBackRef != null) {
                try {
                    this.mFragmentManager = ((Activity) this.mActivityBackRef.get()).getFragmentManager();
                    return this.mFragmentManager;
                } catch (Exception e) {
                    Trace.debug("PebbleWebappBaseActivity", "getFragmentManagerTempRef", e);
                }
            }
            return null;
        }

        private synchronized void createWebappScenes() {
            this.mWebappSceneMapByUniqueId = new HashMap();
            this.mWebappSceneSequenceListAccelerator = new ArrayList();
            for (UUID appUuid : JsKit.jsKitAccess().currentlyRunningJsApplications()) {
                WebviewClientPack clientApp = JsKit.jsKitAccess().getWebappInfoByUuid(appUuid);
                if (clientApp != null) {
                    WebappGenericBaseFragment possibleWebappFragment = null;
                    try {
                        possibleWebappFragment = (WebappGenericBaseFragment) clientApp.mWebviewClient.get();
                    } catch (Exception e) {
                        Trace.debug("PebbleWebappBaseActivity", "createWebappScenes", e);
                    }
                    if (possibleWebappFragment == null) {
                        continue;
                    } else if (!this.mWebappSceneMapByUniqueId.containsKey(Integer.valueOf(possibleWebappFragment.clientUuidAsInt()))) {
                        this.mWebappSceneMapByUniqueId.put(Integer.valueOf(possibleWebappFragment.clientUuidAsInt()), possibleWebappFragment);
                        this.mWebappSceneSequenceListAccelerator.add(possibleWebappFragment);
                    }
                }
            }
        }

        public synchronized WebappGenericBaseFragment getWebappFragmentByUuid(UUID uuid) {
            return (WebappGenericBaseFragment) this.mWebappSceneMapByUniqueId.get(Integer.valueOf(WebappGenericBaseFragment.clientUuidAsInt(uuid)));
        }

        public synchronized int getCount() {
            int size;
            try {
                size = this.mWebappSceneSequenceListAccelerator.size();
            } catch (Exception e) {
                Trace.debug("PebbleWebappBaseActivity", "getCount", e);
                size = 0;
            }
            return size;
        }

        public synchronized UUID[] getAllWebappFragmentUuids() {
            UUID[] uuidArr;
            if (this.mWebappSceneSequenceListAccelerator.size() < 1) {
                uuidArr = new UUID[0];
            } else {
                List<UUID> rv = new ArrayList();
                Iterator i$ = this.mWebappSceneSequenceListAccelerator.iterator();
                while (i$.hasNext()) {
                    WebappGenericBaseFragment f = (WebappGenericBaseFragment) i$.next();
                    if (f != null) {
                        UUID u = f.clientUuid();
                        if (u != null) {
                            rv.add(u);
                        }
                    }
                }
                uuidArr = (UUID[]) rv.toArray(new UUID[rv.size()]);
            }
            return uuidArr;
        }
    }

    protected void onPause() {
        super.onPause();
        PebbleWebappBaseActivity.LogSimpleDebug(this, "+++++++++++++++++ onPause", new Object[0]);
        escapingOutCleanly(DebugEscapesOriginE.onPause);
    }

    protected void onStop() {
        super.onStop();
        PebbleWebappBaseActivity.LogSimpleDebug(this, "+++++++++++++++++ onStop", new Object[0]);
        escapingOutCleanly(DebugEscapesOriginE.onStop);
    }

    protected void onDestroy() {
        super.onDestroy();
        PebbleWebappBaseActivity.LogSimpleDebug(this, "+++++++++++++++++ onDestroy", new Object[0]);
        escapingOutCleanly(DebugEscapesOriginE.onDestroy);
    }

    protected void onResume() {
        super.onResume();
        PebbleWebappBaseActivity.LogSimpleDebug(this, "+++++++++++++++++ onResume", new Object[0]);
        resetDbgBackPressed();
    }

    void resetDbgBackPressed() {
        this.dbgBackPressed = false;
        this.dbgBackPressedTime = 0;
    }

    void dbgBackPressedTrigger() {
        this.dbgBackPressedTime = System.currentTimeMillis();
        this.dbgBackPressed = true;
    }

    String formDbgOriginString(DebugEscapesOriginE dbgEscapeOrigin, boolean resetDbgBackPress) {
        String originStr = dbgEscapeOrigin == null ? DebugEscapesOriginE.__INVALID__.name() : dbgEscapeOrigin.name();
        String backPressTraceTime = this.dbgBackPressed ? "back press " + (System.currentTimeMillis() - this.dbgBackPressedTime) + " ms ago" : "";
        if (resetDbgBackPress) {
            resetDbgBackPressed();
        }
        return originStr + " " + backPressTraceTime;
    }

    public void onBackPressed() {
        dbgBackPressedTrigger();
        finish();
    }

    protected void escapingOutCleanly(DebugEscapesOriginE dbgEscapeOrigin) {
        PebbleWebappBaseActivity.LogSimpleDebug(this, "<<<<<< <<<<<< Escaping out of WebUi ! (origin = " + formDbgOriginString(dbgEscapeOrigin, true) + ") >>>>>> >>>>>>", new Object[0]);
        if (this.mWebappScenePager != null) {
            UUID[] allCurrentWebuiUuids = this.mWebappScenePager.getAllWebappFragmentUuids();
            for (UUID uuid : allCurrentWebuiUuids) {
                try {
                    WebappGenericBaseFragment webappFragment = this.mWebappScenePager.getWebappFragmentByUuid(uuid);
                    if (webappFragment != null) {
                        UUID linkedCreatedByClientId = webappFragment.queryCreatedByLinkedClient();
                        WebviewClientPack clientPack = JsKit.jsKitAccess().getWebappInfoByUuid(uuid);
                        if (!clientPack.isClosing()) {
                            clientPack.setClosing();
                            JsKit.jsKitAccess().setLeaveBehindDataForClient(uuid, "CANCELLED", null);
                            JsKit.jsKitAccess().commitsendLeaveBehindDataForClient(linkedCreatedByClientId, uuid);
                        }
                    }
                } catch (Exception e) {
                    Trace.debug("PebbleWebappBaseActivity", "escapingOutCleanly", e);
                }
            }
            doKillSequenceOnSpecifiedClientUuids(null, allCurrentWebuiUuids);
        }
        finish();
    }

    protected void onCreate(Bundle savedInstanceState) {
        JsAppContextBridge.getInstance().setAppContext(getApplicationContext());
        if (this.mSceneSwitchDelayTimer != null) {
            this.mSceneSwitchDelayTimer.cancel();
            this.mSceneSwitchDelayTimer.purge();
        }
        this.mSceneSwitchDelayTimer = new Timer();
        this.mWebappScenePager = new WebappScenePagerAdapter(this, R.id.webapp_base_activity_target_framelayout);
        onCreateWithView(savedInstanceState);
        runOnUiThread(new Runnable() {
            public void run() {
                PebbleWebUiWebappActivity.this.mWebappScenePager.nextValidFragmentWithManager();
            }
        });
        PebbleWebappBaseActivity.LogSimpleDebug(this, "*************** onCreate", new Object[0]);
        super.onCreate(savedInstanceState);
        postProcessNewIntent(getIntent());
    }

    protected void onCreateWithView(Bundle savedInstanceState) {
        setContentView(R.layout.webapp_base_activity);
        ActionBar actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.hide();
        View mainNav = findViewById(R.id.webapp_base_activity_navlayout);
        View mainFrame = mainNav.findViewById(R.id.webapp_base_activity_target_framelayout);
        this.mNavButtonPrevious = (Button) mainNav.findViewById(R.id.webapp_base_activity_nav_btn_prev);
        this.mNavButtonNext = (Button) mainNav.findViewById(R.id.webapp_base_activity_nav_btn_next);
        if (this.mNavButtonPrevious != null) {
            this.mNavButtonPrevious.setVisibility(8);
            this.mNavButtonPrevious.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    PebbleWebUiWebappActivity.this.mWebappScenePager.previousFragmentWithManager();
                }
            });
        }
        if (this.mNavButtonNext != null) {
            this.mNavButtonNext.setVisibility(8);
            this.mNavButtonNext.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    PebbleWebUiWebappActivity.this.mWebappScenePager.nextFragmentWithManager();
                }
            });
        }
    }

    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        postProcessNewIntent(intent);
    }

    private void postProcessNewIntent(Intent intent) {
        if (this.mWebappScenePager.getCount() < 1) {
            UUID baseNoUiAppUuid = PebbleWebappBaseActivity.extractLinkedClientUuidFromIntentData(intent);
            Intent resultDataIntent = new Intent();
            PebbleWebappBaseActivity.modifyIntentWithRequestedByClientUuid(resultDataIntent, baseNoUiAppUuid, intent == null ? WebappIntentTypeE.__INVALID__ : PebbleWebappBaseActivity.extractIntentTypeFromIntentData(intent));
            setResult(-1, resultDataIntent);
            getFragmentManager().executePendingTransactions();
            runOnUiThread(new Runnable() {
                public void run() {
                    PebbleWebUiWebappActivity.this.finish();
                }
            });
        }
    }

    protected boolean onNewWebappCreationIntent(Intent intent, String paramString) {
        boolean z = true;
        JSONObject jo = null;
        try {
            jo = new JSONObject(paramString);
        } catch (Exception e) {
            Trace.debug("PebbleWebappBaseActivity", "onNewWebappCreationIntent", e);
        }
        if (jo != null) {
            String webappObject = null;
            String loadUrlString = null;
            String requestedByClientId = null;
            boolean useBootstrapScripts = true;
            z = false;
            try {
                webappObject = jo.optString("webappObject", "");
                loadUrlString = jo.optString("loadUrlString", "");
                String appInfoJsonUrlString = jo.optString("appInfoJsonUrlString", "");
                useBootstrapScripts = jo.optBoolean("useBootstrapScripts", true);
                requestedByClientId = jo.optString("requestedByClientId", "");
                z = jo.optBoolean("quietLaunch", false);
            } catch (Exception e2) {
                Trace.debug("PebbleWebappBaseActivity", "onNewWebappCreationIntent", e2);
            }
            if (webappObject.equals(BlankApp.class.getCanonicalName())) {
                WebappGenericBaseFragment g = new BlankApp();
                if (!requestedByClientId.isEmpty()) {
                    g.setCreatedByLinkedClientEntry(requestedByClientId);
                    WebviewClientPack requestedByClientPack = JsKit.jsKitAccess().getWebappInfoByUuid(requestedByClientId);
                    if (requestedByClientPack != null) {
                        requestedByClientPack.setNewSpawnedClient(g.clientUuid());
                    }
                }
                if (useBootstrapScripts) {
                    g.loadUrl(loadUrlString);
                } else {
                    g.loadUrlNoBootstrapScripts(loadUrlString);
                }
                this.mWebappScenePager.addFragment(g);
            }
        }
        return z;
    }

    protected boolean onCloseKillWebappIntent(Intent causedByIntent, String paramString) {
        JSONObject jo = null;
        try {
            jo = new JSONObject(paramString);
        } catch (Exception e) {
            Trace.debug("PebbleWebappBaseActivity", "onCloseKillWebappIntent", e);
        }
        if (jo == null) {
            return true;
        }
        boolean quietKill = false;
        try {
            quietKill = jo.optBoolean("quietKill", false);
        } catch (Exception e2) {
            Trace.debug("PebbleWebappBaseActivity", "onCloseKillWebappIntent", e2);
        }
        doKillSequenceOnSpecifiedClientUuids(causedByIntent, PebbleWebappBaseActivity.extractTargetUuidsFromKillIntentData(paramString));
        return quietKill;
    }

    protected void doKillSequenceOnSpecifiedClientUuids(Intent causedByIntent, UUID[] uuids) {
        for (UUID uuid : uuids) {
            doKillSequenceOnSpecifiedClientUuid(causedByIntent, uuid);
        }
    }

    protected void doKillSequenceOnSpecifiedClientUuid(Intent causedByIntent, UUID uuid) {
        if (uuid != null) {
            try {
                this.mWebappScenePager.removeFragment(uuid);
            } catch (Exception e) {
                Trace.debug("PebbleWebappBaseActivity", "doKillSequenceOnSpecifiedClientUuid", e);
            }
            super.doKillSequenceOnSpecifiedClientUuid(causedByIntent, uuid);
        }
    }
}
